<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订阅名称" prop="subId">
        <el-select v-model="queryParams.subId" placeholder="请选择订阅名称" clearable filterable @change="handleQuery">
          <el-option v-for="item in subOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <!-- <el-form-item label="用户ID" prop="userId">
        <el-input v-model="queryParams.userId" placeholder="请输入用户ID" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->
      <el-form-item label="规则名称" prop="ruleId">
        <el-select v-model="queryParams.ruleId" placeholder="请选择规则" clearable filterable @change="handleQuery">
          <el-option v-for="item in ruleOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="订阅用户" prop="userId">
        <el-select v-model="queryParams.userId" placeholder="请选择用户" clearable filterable @change="handleQuery">
          <el-option v-for="user in userOptions" :key="user.value" :label="user.label" :value="user.value" />
        </el-select>
      </el-form-item> -->

      <!-- <el-form-item label="规则ID" prop="ruleId">
        <el-input v-model="queryParams.ruleId" placeholder="请输入规则ID" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->

      <!-- <el-form-item label="通知方式" prop="notifyMethod">
        <el-input v-model="queryParams.notifyMethod" placeholder="请输入通知方式" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->
      <el-form-item label="通知方式" prop="notifyMethod">
        <el-select v-model="queryParams.notifyMethod" placeholder="请选择通知方式" clearable filterable @change="handleQuery">
          <el-option label="短信" value="短信" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="创建者" prop="createBy">
        <el-input v-model="queryParams.createBy" placeholder="请输入创建者" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->
      <!-- <el-form-item label="创建时间" prop="createTime">
        <el-date-picker clearable v-model="queryParams.createTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item> -->
      <!-- <el-form-item label="更新时间" prop="updateTime">
        <el-date-picker clearable v-model="queryParams.updateTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择更新时间">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['system:usersub:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:usersub:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:usersub:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['system:usersub:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="usersubList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" width="55" align="center" prop="subId" />
      <el-table-column label="订阅名称" align="center" prop="subName" />
      <!-- <el-table-column label="用户ID" align="center" prop="userId" /> -->
      <el-table-column label="规则名称" align="center" prop="ruleName" />
      <el-table-column label="订阅用户" align="center" prop="userName" />
      <!-- <el-table-column label="规则ID" align="center" prop="ruleId" /> -->
      <el-table-column label="通知方式" align="center" prop="notifyMethod" />
      <el-table-column label="创建用户" align="center" prop="createByName" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:usersub:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:usersub:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改用户订阅对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="usersubRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订阅名称" prop="subName">
          <el-input v-model="form.subName" placeholder="请输入订阅名称" />
        </el-form-item>
        <el-form-item label="分配用户" prop="userId">
          <el-select v-model="form.userId" placeholder="请选择用户" clearable filterable>
            <el-option v-for="user in userOptions" :key="user.value" :label="user.label" :value="user.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="关联规则" prop="ruleId">
          <el-select v-model="form.ruleId" placeholder="请选择规则" clearable filterable>
            <el-option v-for="item in ruleOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="通知方式" prop="notifyMethod">
          <el-select v-model="form.notifyMethod" placeholder="请选择通知方式" clearable>
            <el-option label="短信" value="短信" />
          </el-select>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Usersub">
import { listUsersub, getUsersub, delUsersub, addUsersub, updateUsersub } from "@/api/agriculture/znjc/usersub"
import { getUserProfile, getUser, listUser } from "@/api/system/user"
import { listRules, getRules } from "@/api/agriculture/znjc/rules"
import { onMounted, reactive } from 'vue'



const ruleOptions = ref([])  // 用于存储规则下拉数据
const userOptions = ref([])  // 用于存储用户列表下拉数据
const subOptions = ref([])  // 订阅名称下拉框选项


const { proxy } = getCurrentInstance()

const usersubList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {
    notifyMethod: '短信',
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    subId: null,
    userId: null,
    ruleId: null,
    notifyMethod: null,
    subName: null,
    createBy: null,
    createTime: null,
    updateTime: null
  },
  rules: {
    userId: [
      { required: true, message: '用户不能为空', trigger: 'blur' }
    ],
    ruleId: [
      { required: true, message: '规则ID不能为空', trigger: 'blur' }
    ],
    notifyMethod: [
      { required: true, message: '请选择通知方式', trigger: 'change' }
    ],
    subName: [
      { required: true, message: '订阅名称不能为空', trigger: 'change' }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询用户订阅列表 */
async function getList() {
  loading.value = true
  try {
    const response = await listUsersub(queryParams.value)
    usersubList.value = response.rows
    total.value = response.total
    await loadUserNames() // 在获取数据后加载用户名
    await loadRuleNames()// 在获取数据后加载规则名
    await loadUserNamesByUserId() // 在获取数据后加载userId对应用户名
  } catch (error) {
    console.error("获取用户订阅列表失败:", error)
  } finally {
    loading.value = false
  }
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    subId: null,
    userId: null,
    ruleId: null,
    notifyMethod: '短信',
    createBy: null,
    createTime: null,
    updateTime: null
  }
  proxy.resetForm("usersubRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.subId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}


/** 新增按钮操作 */
async function handleAdd() {
  reset()
  //  加载规则选项
  try {
    await loadRuleOptions()
    console.log(loadRuleOptions)
  } catch (error) {
    console.error("加载规则选项失败:", error)
  }

  // 获取当前用户信息设置创建者
  try {
    const res = await getUserProfile()
    form.value.createBy = res.data.userId
  } catch (error) {
    console.error("获取当前用户信息失败:", error)
  }
  open.value = true
  title.value = "添加用户订阅"
}


/** 修改按钮操作 */
async function handleUpdate(row) {
  reset()
  // 加载规则下拉选项
  try {
    await loadRuleOptions()
  } catch (error) {
    console.error("加载规则列表失败:", error)
  }

  // 获取当前订阅记录的数据
  try {
    const _subId = row.subId || ids.value
    const response = await getUsersub(_subId)
    form.value = response.data
    open.value = true
    title.value = "修改用户订阅"
  } catch (error) {
    console.error("获取用户订阅信息失败:", error)
  }
}


/** 提交按钮 */
function submitForm() {
  proxy.$refs["usersubRef"].validate(valid => {
    if (valid) {
      if (form.value.subId != null) {
        updateUsersub(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addUsersub(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _subIds = row.subId || ids.value
  proxy.$modal.confirm('是否确认删除用户订阅编号为"' + _subIds + '"的数据项？').then(function () {
    return delUsersub(_subIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/usersub/export', {
    ...queryParams.value
  }, `usersub_${new Date().getTime()}.xlsx`)
}



/**
 * 根据规则列表中的 createBy 用户ID，异步查询对应用户名并赋值
 */
async function loadUserNames() {
  const promises = usersubList.value.map(async (rule) => {
    if (rule.createBy) {
      try {
        const res = await getUser(rule.createBy)
        rule.createByName = res.data.userName || '未知用户'
      } catch (error) {
        rule.createByName = '查询失败'
        console.error('获取用户失败', error)
      }
    } else {
      rule.createByName = '无用户ID'
    }
  })
  await Promise.all(promises)
}

// 根据每条订阅的 ruleId 去查规则详情，给 ruleName 赋值
async function loadRuleNames() {
  const cache = new Map() // 规则ID缓存，避免重复请求
  const promises = usersubList.value.map(async item => {
    if (item.ruleId) {
      if (cache.has(item.ruleId)) {
        item.ruleName = cache.get(item.ruleId)
      } else {
        try {
          const res = await getRules(item.ruleId)
          const name = res.data.ruleName || '未知规则'
          cache.set(item.ruleId, name)
          item.ruleName = name
        } catch (error) {
          item.ruleName = '查询失败'
          console.error(`获取规则[${item.ruleId}]失败:`, error)
        }
      }
    } else {
      item.ruleName = '无规则ID'
    }
  })
  await Promise.all(promises)
}



// 加载规则列表
async function loadRuleOptions() {
  try {
    // 假设listRules支持传参数
    const res = await listRules({ pageNum: 1, pageSize: 1000 })
    ruleOptions.value = res.rows.map(item => ({
      label: item.ruleName,
      value: item.ruleId
    }))
    console.log(ruleOptions.value)
  } catch (error) {
    console.error("加载规则列表失败:", error)
  }
}

// 组件加载时调用，确保规则下拉选项初始化
onMounted(() => {
  loadRuleOptions()
})


// 异步加载 userId 对应用户名
async function loadUserNamesByUserId() {
  const cache = new Map()  // 缓存，避免重复请求相同userId
  const promises = usersubList.value.map(async (item) => {
    if (item.userId) {
      if (cache.has(item.userId)) {
        item.userName = cache.get(item.userId)
      } else {
        try {
          const res = await getUser(item.userId)
          const name = res.data.userName || '未知用户'
          cache.set(item.userId, name)
          item.userName = name
        } catch (error) {
          item.userName = '查询失败'
          console.error('获取用户失败', error)
        }
      }
    } else {
      item.userName = '无用户ID'
    }
  })
  await Promise.all(promises)
}

// 加载用户列表供下拉框选择
async function loadUserOptions() {
  try {
    const res = await listUser({ pageNum: 1, pageSize: 1000 })  // 大页数避免少量数据
    userOptions.value = res.rows.map(u => ({
      label: u.userName,
      value: u.userId
    }))
  } catch (error) {
    console.error("加载用户列表失败", error)
  }
}
// 加载全部订阅供下拉框选择
async function loadSubOptions() {
  try {
    const res = await listUsersub({ pageNum: 1, pageSize: 1000 })  // 加载全部订阅
    subOptions.value = res.rows.map(sub => ({
      label: sub.subName,
      value: sub.subId
    }))
  } catch (error) {
    console.error("加载订阅名称失败:", error)
  }
}


// 组件挂载时加载用户列表（放到 onMounted 中）
onMounted(() => {
  loadUserOptions()
  loadRuleOptions()
  loadSubOptions()
  getList()
})


getList()
</script>
